﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HotelManageSystem.Domain;
using HotelManageSystem.Domain.Entities;
using HotelManageSystem.Domain.Infrastructure;
using HotelManageSystem.Models;
using Telerik.Web.Mvc;

namespace HotelManageSystem.Controllers
{
    /// <summary>
    /// 员工档案管理的控制器
    /// </summary>
    public class BiographyController : Controller
    {
        private IEmployeeRepository employeeRepository;
        private IUnitOfWork unitOfWork;
        private IDepartmentRepository departmentRepository;
        private IPostRepository postRepository;

        public BiographyController(IEmployeeRepository employeeRepository,
                                   IUnitOfWork unitOfWork,
                                   IDepartmentRepository departmentRepository,
                                   IPostRepository postRepository)
        {
            this.employeeRepository = employeeRepository;
            this.unitOfWork = unitOfWork;
            this.departmentRepository = departmentRepository;
            this.postRepository = postRepository;
        }

        //将Employee转换为BiographyOutline,显示到Telrki的Grid当中
        private IEnumerable<BiographyOutline> EmployeesToBiographyOutline()
        {
            return from employee in employeeRepository.GetAll().AsQueryable()
                   select new BiographyOutline
                              {
                                  ID = employee.ID,
                                  Name = employee.Name,
                                  Sex = employee.Sex,
                                  Department = employee.Department.Name,
                                  Post = employee.Post.Title,
                                  Degree = employee.Degree,
                                  EmployeeStatus=employee.EmployeeStatus 
                              };
        }

        //将Employee的概要数据通过BiographyOutline显示到Grid当中去
        public PartialViewResult Index()
        {
            return PartialView(EmployeesToBiographyOutline());
        }

        //用于分页排序和筛选
        [GridAction]
        public ActionResult TelerikAjax()
        {
            return View(new GridModel(EmployeesToBiographyOutline()));
        }

        //获取编辑的视图
        [HttpGet]
        public PartialViewResult Edit(int id)
        {
            Employee employee = employeeRepository.GetById(id);
            BiographyDetial biographyDetial;
            if (employee != null)
            {
                biographyDetial = new BiographyDetial
                                      {
                                          ID = employee.ID,
                                          Name = employee.Name,
                                          Sex = employee.Sex,

                                          PostId = employee.PostId,
                                          DepartmentId = employee.DepartmentId,
                                          Degree = employee.Degree,

                                          Birthday = employee.Birthday,
                                          JoinTime = employee.JoinTime,
                                          Telephone = employee.Telephone,

                                          Identitycard = employee.Identitycard,
                                          Gradution = employee.Gradution,
                                          BirthPlace = employee.BirthPlace,

                                          Nationality = employee.Nationality,
                                          Status = employee.Status,
                                          PersentAddress = employee.PersentAddress,

                                          HomeAddress = employee.HomeAddress,
                                          Zip = employee.Zip,
                                          EmployeeStatus = employee.EmployeeStatus,
                                          ProbationDates = employee.ProbationDates.ToString()
                                      };
            }
            else
            {
                biographyDetial = new BiographyDetial();
            }

            return PartialView(biographyDetial);
        }

        //接收编辑的表单数据
        [HttpPost]
        public ActionResult Edit(BiographyDetial biographyDetial)
        {
            Employee employee = employeeRepository.GetById(biographyDetial.ID);
            //视图模型通过验证
            if (ModelState.IsValid)
            {
                //ID = biographyDetial.ID;员工编号创建后不能修改(它也是主表)
                employee.Name = biographyDetial.Name;
                employee.Sex = biographyDetial.Sex;

                employee.PostId = biographyDetial.PostId;
                employee.DepartmentId = biographyDetial.DepartmentId;
                employee.Degree = biographyDetial.Degree;

                employee.Birthday = biographyDetial.Birthday;
                employee.JoinTime = biographyDetial.JoinTime;
                employee.Telephone = biographyDetial.Telephone;

                employee.Identitycard = biographyDetial.Identitycard;
                employee.Gradution = biographyDetial.Gradution;
                employee.BirthPlace = biographyDetial.BirthPlace;

                employee.Nationality = biographyDetial.Nationality;
                employee.Status = biographyDetial.Status;
                employee.PersentAddress = biographyDetial.PersentAddress;

                employee.HomeAddress = biographyDetial.HomeAddress;
                employee.Zip = biographyDetial.Zip;
                employee.EmployeeStatus = biographyDetial.EmployeeStatus;
                employee.ProbationDates = Convert.ToInt32(biographyDetial.ProbationDates);


                employeeRepository.Update(employee);
                unitOfWork.Commit();
                Session["url"] = "/Biography/Index";
                return RedirectToAction("Index", "HumanResources");

            }
            else
            {
                //用户输入数据出现错误重新加载页面
                Session["url"] = "/Biography/Index";
                return RedirectToAction("Index", "HumanResources");
            }
        }

        //返回添加员工档案部分视图
        public PartialViewResult Create()
        {
            return PartialView();
        }

        //接收员工档案数据
        [HttpPost]
        public ActionResult Create(BiographyDetial biographyDetial)
        {
            //视图模型通过验证
            if (ModelState.IsValid)
            {
                Employee employee = new Employee()
                                        {
                                            ID = biographyDetial.ID,
                                            Name = biographyDetial.Name,
                                            Sex = biographyDetial.Sex,

                                            PostId = biographyDetial.PostId,
                                            DepartmentId = biographyDetial.DepartmentId,
                                            Degree = biographyDetial.Degree,

                                            Birthday = biographyDetial.Birthday,
                                            JoinTime = biographyDetial.JoinTime,
                                            Telephone = biographyDetial.Telephone,

                                            Identitycard = biographyDetial.Identitycard,
                                            Gradution = biographyDetial.Gradution,
                                            BirthPlace = biographyDetial.BirthPlace,

                                            Nationality = biographyDetial.Nationality,
                                            Status = biographyDetial.Status,
                                            PersentAddress = biographyDetial.PersentAddress,

                                            HomeAddress = biographyDetial.HomeAddress,
                                            Zip = biographyDetial.Zip,
                                            EmployeeStatus = biographyDetial.EmployeeStatus,
                                            ProbationDates = Convert.ToInt32(biographyDetial.ProbationDates)
                                        };

                employeeRepository.Add(employee);
                unitOfWork.Commit();
                Session["url"] = "/Biography/Index";//添加员工的页面在员工添加之后进行自动跳转到员工列表页面
                return RedirectToAction("Index", "HumanResources");

            }
            else
            {
                //用户输入数据出现错误重新加载页面,用户输入的数据会丢失,并且没有提示
                //ModelState.AddModelError("", "你的输入有误");
                Session["url"] = "/Biography/Index";
                return RedirectToAction("Index", "HumanResources");
            }
        }

        //获取部门列表的Json数据,Name用于显示给用户,Value保存的是部门ID,
        //用于保存在员工档案中的外键的ID
        public JsonResult GetDepartments()
        {
            List<DepartmentModel> departments = new List<DepartmentModel>();
            foreach (Department d in departmentRepository.GetAll())
            {
                departments.Add(new DepartmentModel()
                                    {
                                        ID = d.ID,
                                        Name = d.Name
                                    });
            }
            return Json(departments, JsonRequestBehavior.AllowGet);
        }

        //获取所有的职位,保存到Json当中,返回给客户端,用于显示到下拉列表中给用户选择
        public JsonResult GetPosts()
        {
            var posts = from p in postRepository.GetAll().AsQueryable()
                        select new PostModel()
                                   {
                                       ID = p.ID,
                                       Title = p.Title
                                   };
            return Json(posts.ToList(), JsonRequestBehavior.AllowGet);
        }

        //对员工编号进行Ajax验证,不能出现重复的员工编号
        [HttpGet]
        public JsonResult CheckEmployeeId(string id)
        {
            bool exists = employeeRepository.GetMany(e => e.ID == Convert.ToInt32(id)).Count() > 0;
            return Json(!exists, JsonRequestBehavior.AllowGet);
        }
    }
}
